var express = require('express');
var router = express.Router();
var utils = require('../../functions/utils');

router.get('/' , function(req,res)
{
	var html = "<form name='tmpForm' method='post' action='/deleteAccount'></form>";
	html +=	"<script language=javascript>tmpForm.submit();</script>";

	res.writeHead(200 , {'Content-Type' : 'text/html; charset=utf-8'});
	res.end(html);

});

router.post('/' , function(req,res)
{

	var email = req.body.email;
	var reason = req.body.reason;

	var sessionKey = req.session.key;


	if(utils.isValidString(sessionKey))
	{
		var async = require('async');
		async.waterfall([
			function(cb)
			{
				utils.checkManagerSession(sessionKey , cb);
			}
			,function(result , cb) 
			{
				// 실패 - 로그인 페이지 
				if(result == 0)
				{
					utils.notifyManagerSessionExpired(req , res);
				}
				// 성공 - 실제 작업코드.
				else
				{

					var fs = require('fs');
					fs.readFile('./template/deleteAccount' , function(error,data)
					{
						if(error)
						{
							throw error;
						}
						var html = String(data);

						if(utils.isValidString(email))
						{
							global.master_db.connection.getConnection(function(err,connection)
							{
								if(err) throw err;

								var params=[email , reason];

								var sql = "call manage_deleteAccount(?,?,@result); SELECT @result AS result";
								var query = connection.query(sql, params , function (err, rows) 
								{
									connection.release();
									if(err) throw err;

									html = html.split("%MESSAGE%").join(rows[1][0].result);

									res.writeHead(200 , {'Content-Type' : 'text/html; charset=utf-8'});
									res.end(html);

								}); // replica select query

							}); // master connection	

						} // utils.isValidString(email)
						else
						{
								html = html.split("%MESSAGE%").join('');

								res.writeHead(200 , {'Content-Type' : 'text/html; charset=utf-8'});
								res.end(html);
						}

					}); // read template file
				}
			}
		]); //waterfall
	}
	// 암것도 없으면 loginPage
	else
	{
		utils.gotoManagerLoginPage(req , res);
	}
});

module.exports = router;